package com.coder.filter;

//引入Java包
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//实现 Filter 类
public class JspAuthFilter implements Filter {
	
	public void init(FilterConfig config) throws ServletException {
		
		// 获取初始化参数
//		String testParam = config.getInitParameter("test-param");
//		System.out.println("Test Param: " + testParam);
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws java.io.IOException, ServletException {

	      HttpServletRequest req = (HttpServletRequest) request; 
	      HttpServletResponse resp = (HttpServletResponse) response; 
	      HttpSession session = req.getSession(); 

	      Object user = session.getAttribute("currUser");
	      
	      StringBuffer reqUrl = req.getRequestURL();
	      
	      //用户没有登录，且不是登录页面，需要到登录页面，不拦截登录页面
	      if(user==null && reqUrl.indexOf("login.jsp")==-1){
	    	  resp.sendRedirect("/bluebox/login.jsp"); 
	      }else{
		      
	  		// 传递请求道过滤器链
	  		chain.doFilter(request, response);
	      }
	}

	public void destroy() {
		/* 在Filter实例在服务器上被移除前调用。 */
	}
}